import React, { useEffect, useState } from 'react';
import HgBreadCrumb from '../../../components/HgBreadCrumb'
import {Button,Table,Tag,Drawer,Form,Input,Select,Tree, notification} from 'antd'
import{PlusOutlined} from '@ant-design/icons'
import './index.scss'
import service from '../../../api'
import _ from 'lodash'

const Admin = () => {
    
    var [open,setOpen] = useState(false);
    var [loading,setLoading] = useState(false);
    var [adminlist,setAdminlist] = useState([])
    var [checkedKeys,setCheckedKeys] = useState([])
    const [form] = Form.useForm();//获取form引用

    var columns:any = [
        {
            title:'序号',
            render:(_:any,record:any,index:any)=>{
                return index+1;
            }
        },
        {
            title:'账号',
            dataIndex:'adminname'
        },
        {
            title:'账号',
            render:(_:any,record:any,index:any)=>{
                return (
                    <Tag color="#87d068"> { record.role==1?'超级管理员':'管理员' } </Tag>
                );
            }
        },
        {
            title: '操作',
            key: 'price',
            render: (_:any,record:any,index:any) => {
                return (
                    <>
                        <Button className='edit' type="primary" onClick={( )=>{ handleEdit(record) }}>编辑</Button>
                        <Button type="primary" onClick={( )=>{ handleDelete(record.adminid) }}>删除</Button>
                    </>
                )
            },
        }
    ]

    var toAdminAdd = ()=>{
        setOpen(true);
    }
    
    var handleDelete = async (adminid:any)=>{
        setLoading(true);
        var res = await service.admin.admin_delete( {adminid} );
        setLoading(false);
        if( res.data.code == 200 ){
            notification.success({message:'删除成功!',duration:2});
            var newadminlist = _.cloneDeep(adminlist);
            var i:any = newadminlist.findIndex((item:any)=>item.adminid==adminid);
            if( i != -1 ){
                newadminlist.splice(i,1);
            } 
            setAdminlist(newadminlist);
        }else{
            notification.error({message:'删除失败!',duration:2});
        }
    }

    var handleEdit = (record:any)=>{
        setOpen(true);//弹出抽屉

        form.setFieldsValue(record) //回显数据( 树形控件无法回显 )

        setCheckedKeys(record.checkedKeys);//保存权限数据到checkedKeys状态变量
    }
    //
    var onClose = ()=>{
        //清空表单数据
        form.setFieldsValue({adminid:'',adminname:'',password:'',role:'',checkedKeys:[]});
        setCheckedKeys([]);

        setOpen(false);//关闭抽屉
    }

    //表单校验通过时执行
    var onFinish = async (values:any)=>{
        
        console.log(values);
        //通过adminid来区分 新增操作和编辑操作
        if( values.adminid ){ //编辑
            var {adminid,...vals} = values;
            var res = await service.admin.admin_update( vals );
            if( res.data.code == 200 ){
                notification.success({message:'编辑成功!',duration:2});
                //清空表单数据
                //关闭抽屉
                onClose();
            }else{
                notification.error({message:'编辑失败!',duration:2});
            }
            
        }else { //新增
            // 发请求, 新增管理员
            var res = await service.admin.admin_add( values );
            if( res.data.code == 200 ){
                notification.success({message:'新增成功!',duration:2});
                //清空表单数据
                //关闭抽屉
                onClose();
            }else{
                notification.error({message:'新增失败!',duration:2});
            }

        }
    }

    var request_adminlist = async ()=>{
        setLoading(true);
        var res = await service.admin.admin_list();
        setLoading(false);
        setAdminlist(res.data.data);
    }
    useEffect(()=>{
        request_adminlist();
    },[])

    //树形控件的节点数据
    const treeData = [
        {
            title: '首页',
            key: '/index/home'
        },
        {
            title: '轮播图管理',
            key: '2',
            children: [
                {
                    title: '轮播图列表',
                    key: '/index/swiper'
                }
            ]
        },
        {
            title: '账号管理',
            key: '3',
            children: [
                {
                    title: '管理员列表',
                    key: '/index/admin'
                }
            ]
        },
        {
            title: '产品管理',
            key: '4',
            children: [
                {
                    title: '产品列表',
                    key: '/index/pro'
                },
                {
                    title: '秒杀列表',
                    key: '/index/seckill'
                },
                {
                    title: '推荐列表',
                    key: '/index/recommend'
                },
                {
                    title: '筛选列表',
                    key: '/index/filter'
                },
            ]
        },
        {
            title: '数据可视化',
            key: '5',
            children: [
                {
                    title: 'echarts使用',
                    key: '/index/echarts'
                }
            ]
        },
        {
            title: 'excel管理',
            key: '6',
            children: [
                {
                    title: 'excel导入导出',
                    key: '/index/excel'
                }
            ]
        },
        {
            title: '编辑器管理',
            key: '7',
            children: [
                {
                    title: '编辑器使用',
                    key: '/index/editor'
                }
            ]
        },
        {
            title: '地图管理',
            key: '8',
            children: [
                {
                    title: '百度地图',
                    key: '/index/map'
                }
            ]
        }
    ]   
    
    //树形控件 勾选发生改变的回调
    var onCheck = (checkedKeysValue:any)=>{
        console.log('勾选变化了',checkedKeysValue);
        setCheckedKeys(checkedKeysValue);//保存最新的权限到组件状态变量中
        //保存最新的权限到表单的checkedKeys表单项中
        form.setFieldValue('checkedKeys',checkedKeysValue);
    }
    return (
        <div className='admin'>
            <HgBreadCrumb />
            <div className="opts">
                <Button type="primary" onClick={toAdminAdd}>添加管理员<PlusOutlined /></Button>
            </div>
            {/* columns 表格头配置 */}
            {/* dataSource 表格的数据源 */}
            <Table className='swiper-table' size='middle' loading={loading} columns={columns} dataSource={adminlist} />

            {/* 抽屉弹框 */}
            <Drawer title="新增管理员" placement="right" onClose={onClose} open={open}>
                <Form
                    form={form}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    onFinish={onFinish}
                >
                    <Form.Item
                    hidden
                    label="id"
                    name="adminid"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                    label="账号"
                    name="adminname"
                    rules={[{ required: true, message: 'Please input your username!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                    label="密码"
                    name="password"
                    rules={[{ required: true, message: 'Please input your password!' }]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item label="角色" name="role" >
                        <Select
                        options={[
                            { value: 2, label: '管理员' },
                            { value: 1, label: '超级管理员' },
                        ]}
                        />
                    </Form.Item>

                    <Form.Item label="权限" name="checkedKeys">
                        <Tree
                        checkable
                        onCheck={onCheck}
                        checkedKeys={checkedKeys}
                        treeData={treeData}
                        />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            新增管理员
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>
        </div>
    );
};

export default Admin;